package com.idopartx.phonelightning.ui.home

import android.app.AlertDialog
import android.content.ComponentName
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import android.widget.Toast
import com.dotools.umlibrary.UMPostUtils
import com.idopartx.phonelightning.R
import com.idopartx.phonelightning.databinding.FragmentHomeBinding
import com.idopartx.phonelightning.ui.base.BaseFragment
import com.idopartx.phonelightning.ui.home.calllightning.CallLightningActivity
import com.idopartx.phonelightning.ui.home.notification.NotifyLightningActivity
import com.idopartx.phonelightning.ui.home.screen.ScreenLightningActivity
import com.idopartx.phonelightning.ui.home.smslightning.SmsLightningActivity
import com.idopartx.phonelightning.viewmodel.HomeViewModel
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.idopartx.phonelightning.service.SmsService
import com.idopartx.phonelightning.ui.permissionguide.FindAndOpenDialog
import com.idopartx.phonelightning.ui.permissionguide.VivoFloatViewGuideDialog
import com.idopartx.phonelightning.utils.PermissionUtils

class HomeFragment : BaseFragment<FragmentHomeBinding>() {

    override fun initLayoutResId(): Int {
        return R.layout.fragment_home
    }

    override fun onCreate() {
        binding?.click = ClickProxy()
    }

    inner class ClickProxy {
        fun callLightingAction() {

            UMPostUtils.onEvent(requireActivity(), "fp_call_click")


            if (!XXPermissions.isGranted(
                    requireActivity(),
                    Permission.READ_PHONE_STATE,
                    Permission.CAMERA
                )
            ) {
                AlertDialog.Builder(requireActivity())
                    .setTitle("提示")
                    .setMessage("该功能需要相机权限以及电话权限\n如不授权该功能将无法正常使用")
                    .setNegativeButton("我知道了") { dialog, _ ->
                        dialog.dismiss()
                        XXPermissions.with(requireActivity())
                            .permission(Permission.READ_PHONE_STATE, Permission.CAMERA)
                            .request { _, all ->
                                if (all) {
                                    startActivity(
                                        Intent(
                                            requireActivity(),
                                            CallLightningActivity::class.java
                                        )
                                    )
                                }
                            }
                    }
                    .create()
                    .show()
            } else {
                startActivity(
                    Intent(
                        requireActivity(),
                        CallLightningActivity::class.java
                    )
                )
            }
        }

        fun notificationLightningAction() {
            UMPostUtils.onEvent(requireActivity(), "fp_noti_click")

            if (!XXPermissions.isGranted(
                    requireActivity(),
                    Permission.READ_PHONE_STATE, Permission.CAMERA
                ) || !isEnabled()
            ) {
                AlertDialog.Builder(requireActivity())
                    .setTitle("提示")
                    .setMessage("该功能需要相机权限以及通知使用权限。\n如不授权该功能将无法正常使用")
                    .setNegativeButton("我知道了") { dialog, _ ->
                        dialog.dismiss()
                        XXPermissions.with(requireActivity())
                            .permission(Permission.READ_PHONE_STATE, Permission.CAMERA)
                            .request { _, all ->
                                if (all) {
                                    if (!isEnabled()) {
                                        startActivity(Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"))
                                    } else {
                                        startActivity(
                                            Intent(
                                                requireActivity(),
                                                NotifyLightningActivity::class.java
                                            )
                                        )
                                    }
                                }
                            }
                    }
                    .create()
                    .show()
            } else {
                startActivity(
                    Intent(
                        requireActivity(),
                        NotifyLightningActivity::class.java
                    )
                )
            }
        }

        fun messageLightingAction() {

            UMPostUtils.onEvent(requireActivity(), "fp_text_click")

            if (!XXPermissions.isGranted(
                    requireContext(), Permission.CAMERA,
                    Permission.READ_SMS,
                    Permission.RECEIVE_MMS,
                    Permission.READ_CONTACTS
                )
            ) {

                AlertDialog.Builder(requireActivity())
                    .setTitle("提示")
                    .setMessage("该功能需要相机权限以及短信权限。\n如不授权该功能将无法正常使用")
                    .setNegativeButton("我知道了") { dialog, _ ->
                        dialog.dismiss()
                        XXPermissions.with(requireActivity())
                            .permission(
                                Permission.CAMERA,
                                Permission.READ_SMS,
                                Permission.RECEIVE_MMS,
                                Permission.READ_CONTACTS
                            )
                            .request { _, all ->
                                if (all) {

                                    val smsService = Intent(
                                        requireActivity().applicationContext,
                                        SmsService::class.java
                                    )
                                    requireActivity().startService(smsService)

                                    startActivity(
                                        Intent(
                                            requireActivity(),
                                            SmsLightningActivity::class.java
                                        )
                                    )
                                }
                            }
                    }
                    .create()
                    .show()
            } else {

                val smsService = Intent(
                    requireActivity().applicationContext,
                    SmsService::class.java
                )
                requireActivity().startService(smsService)

                startActivity(
                    Intent(
                        requireActivity(),
                        SmsLightningActivity::class.java
                    )
                )
            }


        }

        fun windowLightningAction() {

            UMPostUtils.onEvent(requireActivity(), "fp_call_screen_click")


            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.canDrawOverlays(requireActivity())) {

                    UMPostUtils.onEvent(requireActivity(), "pop_guide_show")


                    AlertDialog.Builder(requireActivity())
                        .setTitle("提示")
                        .setMessage("屏幕闪光功能需要开启悬浮窗。\n如不授权该功能将无法正常使用")
                        .setNeutralButton("立即开启") { dialog, _ ->
                            dialog.dismiss()
                            UMPostUtils.onEvent(requireActivity(), "pop_on")
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                // 由于8.0对系统弹唱权限的限制，需要用户进去设置中找到对应应用设置弹窗权限
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
                                    //8.0
                                    val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                                    //kotlin写法
                                    startActivityForResult(intent, 111)
                                } else {
                                    // 6.0、7.0、9.0
                                    val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                                    intent.data =
                                        Uri.parse("package:${requireActivity().packageName}")
                                    //kotlin写法
                                    startActivityForResult(intent, 111)
                                }
                            }

                        }.setNegativeButton("暂不开启") { dialog, _ ->

                            startActivity(
                                Intent(
                                    requireActivity(), ScreenLightningActivity
                                    ::class.java
                                )
                            )
                            dialog.dismiss()
                        }
                        .create()
                        .show()
                } else {
                    startActivity(
                        Intent(
                            requireActivity(), ScreenLightningActivity
                            ::class.java
                        )
                    )
                }
            } else {
                startActivity(
                    Intent(
                        requireActivity(), ScreenLightningActivity
                        ::class.java
                    )
                )
            }

        }
    }

    // 判断是否打开了通知监听权限
    private fun isEnabled(): Boolean {
        val pkgName = requireActivity().packageName
        val flat = Settings.Secure.getString(
            requireActivity().contentResolver,
            "enabled_notification_listeners"
        )
        if (!TextUtils.isEmpty(flat)) {
            val names = flat.split(":")
            names.forEach {
                val cn = ComponentName.unflattenFromString(it)
                if (cn != null) {
                    if (TextUtils.equals(pkgName, cn.packageName)) {
                        return true
                    }
                }
            }
        }
//        Toast.makeText(requireActivity(), "", Toast.LENGTH_SHORT).show()
        return false
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 111) {
            startActivity(
                Intent(
                    requireActivity(), ScreenLightningActivity
                    ::class.java
                )
            )
        }
    }
}